import { defineStore } from 'pinia'
import { recursionArr } from '@/utils/tools'
import routes from '@/router/routes'
import config from '@/config'

interface userInfoInterface {
  userName: string
  userId: string | number
  token: string
  roleId: string | number
  avatar: string
  menuId: string | number
}
export const useSystemStore = defineStore('system', {
  persist: {
    storage: sessionStorage
  },
  state: () => {
    return {
      userInfo: {} as userInfoInterface,
      menuData: [] as any[],
      locRouteNames: [] as string[]
    }
  },
  getters: {
    menuRouteNames(): string[] {
      return config.useLocRouter ? this.locRouteNames : recursionArr(this.menuData)
    },
    indexPageObj(): indexPageObjInterface {
      return findIndexPageObj(this.menuData)
    }
  },
  actions: {
    // 设置用户信息
    setUserInfo(userInfo: any) {
      this.userInfo = userInfo
    },
    // 存储来自接口的菜单数据
    setMenuListFromApi(menuListFromApi: []) {
      this.menuData = menuListFromApi
    },
    setLocRouteNames() {
      this.locRouteNames = recursionArr(routes)
    }
  }
})

// 获取首页信息
interface indexPageObjInterface {
  name?: string
  meta?: {
    icon?: string
  }
  children?: indexPageObjInterface[]
  [key: string]: any
}
const findIndexPageObj = (menuList: any[]): indexPageObjInterface => {
  const iconsObj = getLocRoutesIcons()
  let target: indexPageObjInterface = {}
  if (menuList.length) {
    target = menuList[0]
    if (target.children && target.children.length) {
      target = findIndexPageObj(target.children)
    }
  }
  if (target.meta) {
    target.meta.icon = iconsObj[target.name as keyof typeof iconsObj]
  }
  return target
}

// 获取路由icon
const getLocRoutesIcons = () => {
  const getIcons = (list: any[], icons: { [attr: string]: any } = {}) => {
    list.forEach(item => {
      if (item.meta && item.meta.icon) {
        const { name } = item
        const { icon } = item.meta
        // 配置属性
        icons[name] = icon

        // 配置children
        if (Array.isArray(item.children) && item.children.length) {
          getIcons(item.children, icons)
        }
      }
    })
    return icons
  }

  // path:/ 内的路由数据
  const rootRoutes: any[] = routes.find(item => item.path == '/')?.children || []
  // 获取最终菜单
  const iconsObj = getIcons(rootRoutes)
  return iconsObj
}
